package controller;

/**
 * @Author Administrator
 * @create 2020.06.19 上午 8:58
 */

import entity.MD5;
import entity.MyResult;
import entity.Role;
import entity.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import service.RoleService;
import service.UsersService;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * 验证码
 */

@Controller
public class CheckCodeServlet {
    @Autowired
    private UsersService usersService;
    @Autowired
    private RoleService roleService;
    @RequestMapping("/checkCode")
    public void checkCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //服务器通知浏览器不要缓存
        response.setHeader("pragma", "no-cache");
        response.setHeader("cache-control", "no-cache");
        response.setHeader("expires", "0");

        //在内存中创建一个长80，宽30的图片，默认黑色背景
        //参数一：长
        //参数二：宽
        //参数三：颜色
        int width = 80;
        int height = 30;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        //获取画笔
        Graphics g = image.getGraphics();
        //设置画笔颜色为灰色
        g.setColor(Color.GRAY);
        //填充图片
        g.fillRect(0, 0, width, height);

        //产生4个随机验证码，12Ey
        String checkCode = getCheckCode();
        //将验证码放入HttpSession中
        request.getSession().setAttribute("CHECKCODE_SERVER", checkCode);

        //设置画笔颜色为黄色
        g.setColor(Color.YELLOW);
        //设置字体的小大
        g.setFont(new Font("黑体", Font.BOLD, 24));
        //向图片上写入验证码
        g.drawString(checkCode, 15, 25);

        //将内存中的图片输出到浏览器
        //参数一：图片对象
        //参数二：图片的格式，如PNG,JPG,GIF
        //参数三：图片输出到哪里去
        ImageIO.write(image, "PNG", response.getOutputStream());
    }


    /**
     * 产生4位随机字符串
     */
    private String getCheckCode() {
        String base = "0123456789ABCDEFGabcdefg";
        int size = base.length();
        Random r = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i <= 4; i++) {
            //产生0到size-1的随机值
            int index = r.nextInt(size);
            //在base字符串中获取下标为index的字符
            char c = base.charAt(index);
            //将c放入到StringBuffer中去
            sb.append(c);
        }
        return sb.toString();
    }

@ResponseBody
@RequestMapping("/go")
    public MyResult login(String account,String password,HttpServletRequest request){
        //验证校验
        String check = request.getParameter("check");
//从sesion中获取验证码
        HttpSession session = request.getSession();
        String checkcode_server = (String) session.getAttribute("CHECKCODE_SERVER");
//        System.out.println("------------------"+check);
//        System.out.println("------------------"+checkcode_server);
//        System.out.println("------------------"+password);
        session.removeAttribute("CHECKCODE_SERVER");
        if(checkcode_server == null || !checkcode_server.equalsIgnoreCase(check)){
            //验证码错误处理逻辑
            return new MyResult(1);
        }
        password = MD5.str2MD5(password);
//    System.out.println("------------------"+password);
    Users users=usersService.selectByAccount(account);
    if(users==null || !users.getPassword().equals(password)){
        session.setAttribute("users",users);
        return new MyResult(2);
    }
    session.setAttribute("admin",users);
//    System.out.println(users.getRole_id()+"================");
    Role role = roleService.selectRoleAndPer(users.getRole_id());
    System.out.println(role);
    System.out.println(users);
    session.setAttribute("role",role);
    users.setLast_login_time(new Date());
    boolean b = usersService.updateTime(users);
    return new MyResult(0);
    }
}

